package com.kabigon.tiny;

import com.rabbitmq.client.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 发送消息
 *
 * @author xu.biao
 * @version v1.0
 * @Package com.kabigon.tiny
 * @data 2022/12/18 16:38
 */
@Slf4j
public class Consumer_Routing2 {


    @SneakyThrows
    public static void main(String[] args) {

        // 1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();

        // 2. 设置参数
        // 默认 localhost
        factory.setHost("192.168.31.132");
        // 默认 5672
        factory.setPort(5672);
        // 虚拟机 默认值 /
        factory.setVirtualHost("/kabigon");
        // 用户名 默认 guest
        factory.setUsername("xubiao");
        // 密码 默认 guest
        factory.setPassword("xubiao");

        // 3. 创建connection
        Connection connection = factory.newConnection();

        // 4. 创建channel
        Channel channel = connection.createChannel();

        // 5. 创建队列Queue
        /**
         * queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete, Map<String, Object> arguments)
         * 参数：
         * queue：队列名称
         * durable：是否持久化，当mq重启后还在
         * exclusive：是否独占
         * autoDelete， 当connection关闭时是否删除队列
         * arguments：参数信息
         */
        //channel.queueDeclare("hello_world", true, false, false, null);

        // 6. 接收消息
        /**
         * basicConsume(String queue, boolean autoAck, Consumer callback)
         * 参数：
         * queue：队列名称
         * autoAck：是否自动确认
         * callback: 回调对象
         */
        Consumer consumer = new DefaultConsumer(channel) {
            /**
             * 回调方法，当收到消息后，会自动执行该方法
             * 1. consumerTag 标识
             * 2. envelope 获取一些信息，交换机、路由key...
             * 3. properties 配置信息
             * 4. body: 数据
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //log.info("consumerTag [{}]", consumerTag);
                //log.info("envelope.Exchange [{}]", envelope.getExchange());
                //log.info("properties [{}]", properties);
                log.info("body [{}]", new String(body));
                log.info("将日志消息打印控制台...");
            }
        };
        String queue2Name = "test_direct_queue2";
        channel.basicConsume(queue2Name, true, consumer);

    }

}
